package com.example.personnel_management_system.service.Impl;

import com.example.personnel_management_system.entity.Roles;
import com.example.personnel_management_system.entity.User;
import com.example.personnel_management_system.mapper.RolesMapper;
import com.example.personnel_management_system.mapper.UserMapper;
import com.example.personnel_management_system.service.IUserService;
import com.example.personnel_management_system.util.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserService implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RolesMapper rolesMapper;
    @Autowired
    private Tool tool;
    @Override
    public User findByIP(User user) {
        if(user.getuID()==null||user.getuPassword()==null)
            return null;
        User target=userMapper.findByUId(user.getuID());
        if(target==null)
        return null;
        String password=tool.MD5(target.getSalt(),user.getuPassword());
        if(password.equals(target.getuPassword())){
            return target;
        }
        return null;
    }

    @Override
    public void insert(User user) {
        user.setSalt(UUID.randomUUID().toString().toUpperCase());
        user.setuPassword(tool.MD5(user.getSalt(),user.getuPassword()));
        Roles roles= new Roles();
        roles.setrType("普通用户");
        roles.setrName(user.getuName());
        Integer id=userMapper.findLastUId().getuID()+1;
        roles.setrID(id);
        rolesMapper.insert(roles);
        user.setrID(roles.getrID());
        userMapper.insert(user);
        user.setuID(roles.getrID());
    }
}
